<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Image;
use app\admin\service\Meeting as MeetingService;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 会议
 */
class Meeting extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        //$defaultWhere = $this->getDefaultWhere();
        //$this->defaultWhere = $defaultWhere;

        $this->searchFields = [
            'title' => [
                'label'     => '会议主题',
                'field'     => 'title',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'

            ],
        ];
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                //$model = $model->where($this->defaultWhere);
                $where = array_merge($where, $this->defaultWhere);
            }

            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            $count = $model->where($where)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){
        $number = [];
        for($i = 1 ; $i<=60 ; $i++)
        {
            $number []= $i;
        }
        $this->assign('number',$number);
        return view();
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);
        $number = [];
        for($i = 1 ; $i<=60 ; $i++)
        {
            $number []= $i;
        }
        $this->assign('number',$number);
        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        $info->date = date('Y-m-d', strtotime($info->startTime));
        $info->startTime2 = substr($info->startTime, 11);
        $info->endTime2 = substr($info->endTime, 11);

        if ($info['remind'] <= 60 * 60 *24){
            //天
            $info['time'] =  $info['remind'] / 60 / 24  ;
            $info['shijian'] = 3;
        }

        if ($info['remind'] <= 60 * 60){
            //小时
            $info['time'] =  $info['remind'] / 60 ;
            $info['shijian'] = 2;
        }

        if ($info['remind'] <= 60){
            //分钟
            $info['time'] = $info['remind'];
            $info['shijian'] = 1;
        }

        $this->assign('info',$info);
        return $this->view->fetch('edit', [
            'info' => $info,
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param(),
            'pathtype' => 'edit'
        ]);
    }

    /**
     * Add/Edit Post
     */
    public function savePost(Request $request){
        $model = model($this->model);
        if ($request->isAjax()) {
            $data = $request->param();

            $data['startTime'] = date('Y-m-d H:i:s',strtotime($data['date'] . ' ' . $data['startTime']));
            $data['endTime'] = date('Y-m-d H:i:s',strtotime($data['date'] . ' ' . $data['endTime']));
            //$data['tenantId'] = $this->admin->tenantId;

            if ($data['shijian'] == 1){
                //分钟
                $data['remind'] = $data['time'];
            }
            if ($data['shijian'] == 2){
                //小时
                $data['remind'] = $data['time'] * 60 ;
            }
            if ($data['shijian'] == 3){
                //天
                $data['remind'] = $data['time'] * 60 * 24 ;
            }

            if(isset($data['id']) && $data['id']){
                $data['updateDate'] = date('Y-m-d H:i:s',time());
                //$data['updateOper'] = $this->admin->id;

                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                if($result !== false) {
                    return json(['code' => 1, 'msg' => '保存成功！', 'id' => $data['id'], 'url' => url('admin/' . strtolower($this->model) . '/index')]);
                } else {
                    return json(['code' => 0, 'msg' => $model->getError()]);
                }
            }

            // Insert data
            $data['id'] = Helper::getUUID();
            $data['status'] = 1;
            $data['createDate'] = date('Y-m-d H:i:s',time());
            $data['createOper'] = $this->admin->id;
            // 生成会议签到二维码
            $data['signCode'] = MeetingService::createMeetingCode($data['id'], $tenantId='');
            if(!$data['signCode']){
                return json(['code' => 0, 'msg' => '生成会议签到二维码失败！']);
            }

            $result = $model->save($data);

            if($result !== false) {
                return json(['code' => 1, 'msg' => '添加成功！', 'id' => $data['id'], 'url' => url('admin/' . strtolower($this->model) . '/index')]);
            } else {
                return json(['code' => 0, 'msg' => $model->getError()]);
            }
        } else {
            return json(['code' => 0, 'msg' => '请求方式不正确！']);
        }
    }

    /**
     * 是否确认
     */
    public function detail(Request $request){
        $model = model($this->model);
        $param = $request->param();
        if ($request->isAjax()){
            $id = $param['id'];
            $model = model('joinmeeting');
            $data = $model->alias('a')
                ->where(['meetingId'=>$id])
                ->join('user u','a.memberId = u.id')
                ->select();
            foreach($data as $v){
                if ($v['isNotarize'] == 1){
                    $v['isNotarize'] = '确认';
                }elseif($v['isNotarize'] == 2){
                    $v['isNotarize'] = '未确认';
                }else{
                    $v['isNotarize'] = '不参加';
                }
            }
            $count = count($data);
            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $data,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];
            return json($result);
        }
        $id = $param['id'];
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        // 参会人员
        $joinmeetingDB = model('joinmeeting');
        $join = [
            ['user m', 'a.memberId = m.id'],
            //['__ORGANIZATION__ o', 'm.organizationId = o.id'],
        ];
        $fields = 'a.isSign,a.isNotarize,m.p_name';

        $info->joinmeeting = $joinmeetingDB->alias('a')
            ->where(['meetingId' => $id])
            ->field($fields)
            ->join($join)
            ->order('a.createDate ASC')
            ->select();
        $model = model('user');
        //$info->endTime2 = strtotime($info->endTime);
        $info->endTime2= substr($info->endTime, 11);
        $organization = $model->where(['id'=>$info['createOper']])->field('p_name')->find();
        $info->organization = $organization->p_name;

        $this->assign('info',$info);

        return view();
    }

    /**
     * Delete
     */
    public function delete(Request $request){
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');

        if($id){
            Db::startTrans();
            try{
                $result = $model->where('id', $id)->delete();

                if($result !== false){
                    // 删除参会人员
                    $res = model('joinmeeting')->where(['meetingId' => $id])->delete();
                    if($res === false){
                        Db::rollback();
                        return $this->error('删除参会人员失败！', 'admin/' . strtolower($this->model) . '/index');
                    }

                    Db::commit();
                    return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['title']) && $filter['title']){
                $where['title'] = ['like', '%'.$filter['title'].'%'];
            }
        }

        return $where;
    }

    /**
     * 成员列表
     * @return \think\response\Json
     */
    public function memberlist(){
        $request = $this->request;
        $param = $request->param();
        $model = model('user');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        $where = [
            'status' => 1,
            'type' => 1
        ];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['name']) && $filter['name']){
                $where['p_name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        $list = $model->alias('a')->where($where)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 参加会议人员 列表
     * @return \think\response\Json
     */
    public function joinmeetingList(){
        $request = $this->request;
        $param = $request->param();
        $model = model('Joinmeeting');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        if(empty($param['id'])){
            $result = [
                'status' => '0',
                'draw' => $param['draw'],
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
            ];
            return json($result);
        }
        $where = [
            'meetingId' => $param['id']
        ];
        if(isset($param['isSign']) && $param['isSign']){
            $where['isSign'] = $param['isSign'];
        }

        $join = [
            ['user m', 'a.memberId = m.id'],
        ];
        $field = 'a.*,  m.p_name,m.p_imgUrl,m.duties';
        $list = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->join($join)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 添加参会人员
     */
    public function addJoinmeeting(Request $request){
        $model = model('Joinmeeting');

        //save data
        if ($request->isAjax()) {
            $params = $this->request->param();

            if(!$params['meetingId']){
                return json(['code' => 0, 'msg' => '添加失败！']);
            }

            //$ids = $params['id'];
            $ids = explode(',', $params['ids']);
            $data = [];
            $result = true;
            foreach ($ids as $key => $id) {
                $data['meetingId'] = $params['meetingId'];
                $data['memberId'] = $id;
                // 是否已参加
                $isJoin = $model->where($data)->field('memberId')->find();
                if($isJoin){
                    continue;
                }
                $data['id'] = Helper::getUUID();
                $data['createDate'] = date('Y-m-d H:i:s',time());
                $data['isSign'] = 2;

                $result = $model->insert($data);
            }

            if($result !== false) {
                return json(['code' => 1, 'msg' => '添加成功！', 'id' => $data['id']]);
            } else {
                return json(['code' => 0, 'msg' => $model->getError()]);
            }
        } else {
            return json(['code' => 0, 'msg' => '请求方式不正确！']);
        }
    }

    /**
     * 删除参会人员
     */
    public function delJoinmeeting(){
        $model = model('Joinmeeting');

        $request = $this->request;
        $id = $request->param('id');

        // 删除一条
        $info = $model->find(['id', $id]);
        if(!$info){
            return json(['code' => 0, 'msg' => 'error']);
        }
        $result = $model->where('id', $id)->delete();

        if($result !== false){
            return json(['code' => 1, 'msg' => '删除成功！']);
        }else{
            return json(['code' => 0, 'msg' => '删除失败']);
        }
    }

    /**
     * 会议签到
     */
    public function sign(Request $request)
    {
        $model = model($this->model);
        $param = $request->param();
        if ($request->isAjax()){
            $id = $param['id'];
            $model = model('joinmeeting');
            $data = $model->alias('a')
                ->where(['meetingId'=>$id])
                ->join('user u','a.memberId = u.id')
                ->select();
            foreach($data as $v){
                if ($v['isSign'] == 1){
                    $v['isNotarize'] = '签到';
                }else{
                    $v['isNotarize'] = '未签到';
                }
                $v['notarizeDate'] = $v['signDate'];
            }
            $count = count($data);
            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $data,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }
        $id = $param['id'];
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        // 参会人员
        $joinmeetingDB = model('joinmeeting');
        $join = [
            ['user m', 'a.memberId = m.id'],
            //['__ORGANIZATION__ o', 'm.organizationId = o.id'],
        ];
        $fields = 'a.isSign,a.isNotarize,m.p_name';

        $info->joinmeeting = $joinmeetingDB->alias('a')
            ->where(['meetingId' => $id])
            ->field($fields)
            ->join($join)
            ->order('a.createDate ASC')
            ->select();
        $model = model('user');
        //$info->endTime2 = strtotime($info->endTime);
        $info->endTime2= substr($info->endTime, 11);
        $organization = $model->where(['id'=>$info['createOper']])->field('p_name')->find();
        $info->organization = $organization->p_name;

        $this->assign('info',$info);

        return view();
    }
}